package com.gitee.ywj1352.nettyserver.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author yangwenjie.a
 */
public class ServerSkeleton {

    public static final Logger LOGGER = LoggerFactory.getLogger(ServerSkeleton.class);

    public static void main(String[] args) {

        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.option(NioChannelOption.SO_BACKLOG, 1024);
        serverBootstrap.childOption(NioChannelOption.TCP_NODELAY, true);
        serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));

        //boss线程组设置
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(0, new DefaultThreadFactory("boss"));
        NioEventLoopGroup workGroup = new NioEventLoopGroup(0, new DefaultThreadFactory("worker"));

        //工作线程组设置
        UnorderedThreadPoolEventExecutor businessGroup =
            new UnorderedThreadPoolEventExecutor(10, new DefaultThreadFactory("business"));
        NioEventLoopGroup eventLoopGroupForTrafficShaping = new NioEventLoopGroup(0, new DefaultThreadFactory("TS"));

        serverBootstrap.group(bossGroup, workGroup);

        serverBootstrap.childHandler(new CoreChannelInitializer());

        ChannelFuture channelFuture = null;
        try {
            channelFuture = serverBootstrap.bind(8848).sync();
            LOGGER.info("bind port sync over");
            channelFuture.channel().closeFuture().sync();
            LOGGER.info("channelFuture sync over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            businessGroup.shutdownGracefully();
            eventLoopGroupForTrafficShaping.shutdownGracefully();
        }
    }

}
